package com.jt.tenant.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SectionIndexer;
import android.widget.Spinner;
import android.widget.TextView;

import com.jt.tenant.R;
import com.jt.tenant.adapter.CarModelsAdapter;
import com.jt.tenant.adapter.CarSeriesAdapter;
import com.jt.tenant.adapter.ChooseModels2Adapter;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.choosemodels.CharacterParser;
import com.jt.tenant.choosemodels.GroupMemberBean;
import com.jt.tenant.choosemodels.PinyinComparator;
import com.jt.tenant.choosemodels.SideBar;
import com.jt.tenant.choosemodels.SortGroupMemberAdapter;
import com.jt.tenant.conn.GetCarBrand;
import com.jt.tenant.conn.GetCarModels;
import com.jt.tenant.conn.GetCarSeries;
import com.jt.tenant.choosemodels.SideBar.OnTouchingLetterChangedListener;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ChooseModelsActivity extends JTActivity implements SectionIndexer,CarModelsAdapter.ItemClick,CarModelsAdapter.RightSliding {
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private TextView title_name;
    private SortGroupMemberAdapter adapter;
    private PopupWindow popupWindow, cmPopupWindow;
    private LinearLayout titleLayout;
    private FrameLayout fl_car_brand;
    private TextView title;
    private GetCarBrand getCarBrand;
    private GetCarSeries getCarSeries;
    private GetCarModels getCarModels;
    private ListView pop_car_series;
    private List<GetCarSeries.CSList> mCSList = new ArrayList<>();
    private CarSeriesAdapter carSeriesAdapter;
    private ListView pop_car_models;
    private List<GetCarModels.CMList> mCMList = new ArrayList<>();
    private List<GetCarModels.CMList> mCMList_all = new ArrayList<>();
    private CarModelsAdapter carModelsAdapter;
    private List<GetCarModels.MList> mTMList = new ArrayList<>();
    private Spinner carTMSpinner;
    private ChooseModels2Adapter carTMAdapter;
    private List<GetCarModels.MList> mDMList = new ArrayList<>();
    private Spinner carDMSpinner;
    private ChooseModels2Adapter carDMAdapter;
    private String DM = "A", TM = "A";
    final int RIGHT = 0, LEFT = 1;

    /**
     * 上次第一个可见元素，用于滚动时记录标识。
     */
    private int lastFirstVisibleItem = -1;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<GroupMemberBean> SourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_models);
        initViews();
    }

    private void initViews() {
        (title_name = (TextView) findViewById(R.id.tv_title_name)).setText("选择车辆型号");
        titleLayout = (LinearLayout) findViewById(R.id.title_layout);
        title = (TextView) this.findViewById(R.id.title_layout_catalog);
        fl_car_brand = (FrameLayout) findViewById(R.id.fl_car_brand);
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, final long id) {
                // 这里要利用adapter.getItem(position)来获取当前position所对应的对象
                // TODO Auto-generated method stub
                getPopupWindow(position);

                // 位置显示方式
                View rootview = LayoutInflater.from(ChooseModelsActivity.this).inflate(R.layout.activity_choose_models, null);

                popupWindow.showAtLocation(rootview, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);

            }
        });

        getCarBrand = new GetCarBrand(new AsyCallBack<GetCarBrand.Info>() {

            @Override
            public void onSuccess(String toast, int type, GetCarBrand.Info info) throws Exception {

                super.onSuccess(toast, type, info);

                if (info.msg.equals("000")) {

                    SourceDateList = filledData(info.cbLists);

                    initData();

                } else {

                    UtilToast.show(ChooseModelsActivity.this, toast);

                }
            }
        });

        getCarBrand.execute(ChooseModelsActivity.this);

    }

    private void initData() {

        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortGroupMemberAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);
        sortListView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                int section = getSectionForPosition(firstVisibleItem);
                int nextSection = getSectionForPosition(firstVisibleItem + 1);
                int nextSecPosition = getPositionForSection(+nextSection);
                if (firstVisibleItem != lastFirstVisibleItem) {
                    MarginLayoutParams params = (MarginLayoutParams) titleLayout
                            .getLayoutParams();
                    params.topMargin = 0;
                    titleLayout.setLayoutParams(params);
                    title.setText(SourceDateList.get(
                            getPositionForSection(section)).getSortLetters());
                }
                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = titleLayout.getHeight();
                        int bottom = childView.getBottom();
                        MarginLayoutParams params = (MarginLayoutParams) titleLayout
                                .getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            titleLayout.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                titleLayout.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            }
        });

    }

    /**
     * 为ListView填充数据
     *
     * @param lists
     * @return
     */
    private List<GroupMemberBean> filledData(List<GetCarBrand.CBList> lists) {
        List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

        for (int i = 0; i < lists.size(); i++) {
            GroupMemberBean sortModel = new GroupMemberBean();
            sortModel.setName(lists.get(i).NAME);
            sortModel.setid(lists.get(i).ID);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(lists.get(i).NAME);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<GroupMemberBean> filterDateList = new ArrayList<GroupMemberBean>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (GroupMemberBean sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(
                        filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return SourceDateList.get(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < SourceDateList.size(); i++) {
            String sortStr = SourceDateList.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 创建车系PopupWindow
     */
    protected void initPopuptWindow(int position) {
        // TODO Auto-generated method stub

        // 获取自定义布局文件pop.xml的视图
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popwindow_car_series, null,
                false);
        // 创建PopupWindow实例,设置分别是宽度和高度
        WindowManager wm = this.getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height = fl_car_brand.getHeight();
        popupWindow = new PopupWindow(popupWindow_view, width / 4 * 3, height, true);
        // 设置动画效果
        popupWindow.setAnimationStyle(R.style.AnimationFade);
        //点击其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        // pop.xml视图里面的控件
        pop_car_series = (ListView) popupWindow_view.findViewById(R.id.pop_car_series);
        carSeriesAdapter = new CarSeriesAdapter(this, mCSList);
        pop_car_series.setAdapter(carSeriesAdapter);
        getCarSeries = new GetCarSeries(((GroupMemberBean) adapter.getItem(position)).getId(), new AsyCallBack<GetCarSeries.Info>() {

            @Override
            public void onSuccess(String toast, int type, GetCarSeries.Info info) throws Exception {

                super.onSuccess(toast, type, info);

                if (info.msg.equals("000")) {

                    mCSList.clear();

                    mCSList.addAll(info.csLists);

                    carSeriesAdapter.notifyDataSetChanged();

                } else {

                    mCSList.clear();

                    UtilToast.show(ChooseModelsActivity.this, toast);

                }


            }

            @Override
            public void onFail(String toast, int type) throws Exception {

                super.onFail(toast, type);

                UtilToast.show(ChooseModelsActivity.this, toast);

                finish();

            }
        });
        getCarSeries.execute(ChooseModelsActivity.this);

        // pop.xml视图里面的控件触发的事件
        pop_car_series.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

                getCMPopupWindow(pos);

                View cm_rootview = JTApplication.ScaleScreenHelper.loadView((ViewGroup) getLayoutInflater().inflate(R.layout.activity_choose_models, null));

                cmPopupWindow.showAtLocation(cm_rootview, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);

            }
        });
    }

    /***
     * 获取车系PopupWindow实例
     */
    private void getPopupWindow(int position) {

//        if (null != popupWindow) {
//            popupWindow.dismiss();
//            return;
//        } else {

        popupWindow = null;
            initPopuptWindow(position);
//        }
    }

    /**
     * 创建车型PopupWindow
     */
    protected void initCMPopuptWindow(int position) {
        // TODO Auto-generated method stub

        // 获取自定义布局文件pop.xml的视图
        View cmPopupWindow_view = JTApplication.ScaleScreenHelper.loadView((ViewGroup) getLayoutInflater().inflate(R.layout.popwindow_car_models, null,
                false));
        // 创建PopupWindow实例,设置分别是宽度和高度
        WindowManager wm1 = this.getWindowManager();

        int width = wm1.getDefaultDisplay().getWidth();
        int height = fl_car_brand.getHeight();
        cmPopupWindow = new PopupWindow(cmPopupWindow_view, width, height, true);
        // 设置动画效果
        cmPopupWindow.setAnimationStyle(R.style.AnimationFade);
        //点击其他地方消失
        cmPopupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (cmPopupWindow != null && cmPopupWindow.isShowing()) {
                    cmPopupWindow.dismiss();
                    cmPopupWindow = null;
                }
                return false;
            }
        });

        // pop.xml视图里面的控件
        pop_car_models = (ListView) cmPopupWindow_view.findViewById(R.id.pop_car_models);
        carTMSpinner = (Spinner) cmPopupWindow_view.findViewById(R.id.pop_cm_tm);
        carTMSpinner.setAdapter(carTMAdapter = new ChooseModels2Adapter(context, mTMList));
        carDMSpinner = (Spinner) cmPopupWindow_view.findViewById(R.id.pop_cm_dm);
        carDMSpinner.setAdapter(carDMAdapter = new ChooseModels2Adapter(context, mDMList));
        carModelsAdapter = new CarModelsAdapter(ChooseModelsActivity.this, mCMList,ChooseModelsActivity.this,ChooseModelsActivity.this);
        pop_car_models.setAdapter(carModelsAdapter);
        getCarModels = new GetCarModels(mCSList.get(position).BRANDID, mCSList.get(position).ID, new AsyCallBack<GetCarModels.Info>() {

            @Override
            public void onSuccess(String toast, int type, GetCarModels.Info info) throws Exception {

                if (info.msg.equals("000")) {

                    mCMList.clear();

                    mCMList_all.clear();

                    mDMList.clear();

                    mTMList.clear();

                    mCMList.addAll(info.cmLists);

                    mCMList_all.addAll(info.cmLists);

                    mDMList.addAll(info.dmLists);

                    mTMList.addAll(info.tmLists);

                    carTMAdapter.notifyDataSetChanged();

                    carDMAdapter.notifyDataSetChanged();

                    carModelsAdapter.notifyDataSetChanged();


                } else {

                    mCMList.clear();

                    UtilToast.show(ChooseModelsActivity.this, toast);

                }

            }
        });
        getCarModels.execute(ChooseModelsActivity.this);
        // pop.xml视图里面的控件触发的事件

        carDMSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

                DM = mDMList.get(position).NAME;

                TextView tv = (TextView) v.findViewById(R.id.tv_cm_model);

                tv.setTextColor(Color.WHITE);

                refurbishModelList();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        carTMSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                TM = mTMList.get(position).NAME;

                TextView tv = (TextView) view.findViewById(R.id.tv_cm_model);

                tv.setTextColor(Color.WHITE);

                refurbishModelList();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    /***
     * 获取车型PopupWindow实例
     */
    private void getCMPopupWindow(int position) {

//        if (null != cmPopupWindow) {
//            cmPopupWindow.dismiss();
//            return;
//        } else {
        cmPopupWindow = null;
            initCMPopuptWindow(position);
//        }
    }

    //刷新车型列表
    private void refurbishModelList() {

        List<GetCarModels.CMList> list = new ArrayList<>();

        for (int i = 0; i < mCMList_all.size(); i++) {

            if ((mCMList_all.get(i).DISPLACEMENT.equals(DM) | DM.equals("全部排量")) && (mCMList_all.get(i).TRANSMISSION.equals(TM) | TM.equals("变速箱种类"))) {

                list.add(mCMList_all.get(i));

            }

        }

        mCMList.clear();

        mCMList.addAll(list);

        carModelsAdapter.notifyDataSetChanged();

    }

    public void itemClick(int position) {

        Bundle bundle = new Bundle();

        bundle.putString("BRAND",mCMList.get(position).BRAND);

        bundle.putString("CS", mCMList.get(position).SERIES);

        bundle.putString("CM", mCMList.get(position).NAME);

        bundle.putString("DM", mCMList.get(position).DISPLACEMENT);

        bundle.putString("TM", mCMList.get(position).TRANSMISSION);

        bundle.putString("YEAR", mCMList.get(position).MODELYEAR);

        Intent intent = new Intent();

        intent.putExtras(bundle);

        setResult(RESULT_OK, intent);

        finish();

    }

    public void rightSliding(){

        if (cmPopupWindow != null && cmPopupWindow.isShowing()) {
            cmPopupWindow.dismiss();
            cmPopupWindow = null;
        }

    }


}



